#include "mesh_renderer.h"
#include "tiny_gltf.h"
#include <iostream>
#include "engine/utils/file_utils.h"

namespace kanon
{
    MeshRenderer::MeshRenderer()
    {
        std::string vertex_shader_path = FileUtils::getShaderPath("mesh_renderer.vs");
        std::string fragment_shader_path = FileUtils::getShaderPath("mesh_renderer.fs");
        shader = Shader::FromShaderFiles(vertex_shader_path, fragment_shader_path);
        camera = nullptr;
    }

    void MeshRenderer::Begin()
    {
        glClearColor(0.2f, 0.3f, 0.4f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        shader->Bind();
    }

    void MeshRenderer::End()
    {
        shader->Unbind();
    }

    void MeshRenderer::SetCamera(const std::shared_ptr<Camera3d>& cam)
    {
        camera = cam;
    }

    void MeshRenderer::Render(const std::shared_ptr<Mesh>& mesh)
    {
        // TODO: attach texture, multiple texture support.

        mesh->Draw();
    }

    void MeshRenderer::Render(const std::shared_ptr<Model>& model)
    {
        if (camera)
        {
            glm::mat4 view = camera->getViewMatrix();
            glm::mat4 proj = camera->getProjectionMatrix();
            shader->set_matrix("view", view);
            shader->set_matrix("projection", proj);
        }

        for (auto& mesh : model->meshes)
            Render(mesh);
    }

}